package com.example.pet.controller;

import com.example.pet.entity.Pet;
import com.example.pet.entity.Shoppingcart;
import com.example.pet.service.PetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.extern.slf4j.Slf4j;
import org.apache.tika.Tika;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;


@RestControllerAdvice
@RequestMapping("/pet")
@Api(tags = "宠物失寻控制层")
@Slf4j
public class PetController {
    @Resource
    private PetService petService;

    @Value("${file.upload-path}")
    private String path;
    @Value("${server.servlet.multipart.max-file-size}")
    private String maxSize;

    //    @ExceptionHandler(FileSizeLimitExceededException.class)//处理文件大小超出限制异常
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
        return "文件大小超过限制";
    }

    @ApiOperation(value = "添加宠物失寻", notes = "添加宠物失寻")
    @PostMapping("/add")
    public Object que(Pet pet, @RequestPart(value = "file", required = true)
    @Parameter(description = "图片上传", required = true, content = @Content(mediaType = "multipart/form-data")) MultipartFile[] file) throws IOException {
        if (pet.getPetName().equals("")) {
            return "宠物名不能为空";
        } else if (pet.getPositioning().equals("")) {
            return "定位不能为空";
        } else if (pet.getSpecies().equals("")) {
            return "种类不能为空";
        } else if (pet.getAge() == null) {
            return "年龄不能为空";
        } else if (pet.getGender().equals("")) {
            return "性别不能为空";
        }
        List<String> list = new ArrayList<>();


        for (MultipartFile multipartFile : file) {

            String uuid = UUID.randomUUID().toString();
            String originalFilename = multipartFile.getOriginalFilename();
            String fix = originalFilename.substring(originalFilename.lastIndexOf("."));

            if (fix.equals(".jpg") || fix.equals(".png") || fix.equals(".jpeg") || fix.equals(".webp") ||
                    fix.equals(".JPG") || fix.equals(".PNG") || fix.equals(".JPEG")) {
                System.out.println("文件格式正确");
            } else {
                return "文件格式错误为 jpg/png/jpeg/webp";
            }

            String fileName = uuid + fix;
            String pathName = path + fileName;
            String url = "http://43.136.137.117:5000" + "/" + fileName;
            File file1 = new File(pathName);
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }

            try (InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream())) {
                // 使用Apache Tika检测文件类型
                Tika tika = new Tika();
                String detectedType = tika.detect(inputStream);// 文件类型 image/png

                if (!StringUtils.startsWithIgnoreCase(detectedType, "image/")) { // 文件类型不是图片
                    return "文件不是有效的图片";
                }

                // 继续处理有效的图片
                // ...

                FileCopyUtils.copy(multipartFile.getBytes(), file1);
                list.add(url);
            } catch (IOException e) {
                return "文件上传失败";
            }
        }
        if (pet.getUserId() == null || pet.getUserId() == 0) {
            return "Uid";
        }
        String petPicture = list.toString();
        pet.setPetPicture(petPicture);

        boolean add = petService.add(pet);
        return add;

    }

    @ApiOperation(value = "查询所有宠物", notes = "查询所有宠物")
    @PostMapping("/queAll")
    public Object queAll(Integer userId) {
        if (userId == null || userId == 0) {
            return "Uid";
        }
        return petService.queryAll(userId);
    }
}
